<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入昵称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="queryParams.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" prop="regTime">
        <el-date-picker clearable
                        v-model="queryParams.regTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择注册时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:user_m:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:user_m:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:user_m:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:user_m:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="user_mList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id(主键)" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="密码" align="center" prop="password" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template #default="scope">
          <!-- 使用 img 标签展示头像，默认图为占位图 -->
          <img
              :src="scope.row.avatar || 'https://picsum.photos/200/200'"
          class="avatar-img"
          title="点击查看大图"
          @click="viewAvatar(scope.row.avatar)"
          />
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="regTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.regTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="默认收货地址id" align="center" prop="defaultAddrId" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="car_user_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否删除" align="center" prop="deleted" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user_m:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user_m:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 头像大图预览弹窗 -->
    <el-dialog
        title="头像预览"
        v-model="showAvatarDialog"
        width="80%"
        append-to-body
    >
      <div style="text-align: center; padding: 20px;">
        <img :src="previewAvatar" style="max-width: 100%; max-height: 80vh;" />
      </div>
    </el-dialog>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="user_mRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号(不能为空)" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <userAvatar
              :userId="form?.id"
              :currentAvatar="form?.avatar"
              @avatarUpdated="handleAvatarUpdated"
          />
        </el-form-item>
        <el-form-item label="注册时间" prop="regTime">
          <el-date-picker clearable
                          v-model="form.regTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择注册时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="默认收货地址id" prop="defaultAddrId">
          <el-input v-model="form.defaultAddrId" placeholder="请输入默认收货地址id" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in car_user_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否删除" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入是否删除" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User_m">
import { ref } from 'vue';
import { listUser_m, getUser_m, delUser_m, addUser_m, updateUser_m} from "@/api/system/appuser.js";
import userAvatar from "./userAvatar"
// 引入弹窗组件
import { ElDialog } from 'element-plus';

const { proxy } = getCurrentInstance()
const { car_user_status } = proxy.useDict('car_user_status')

const user_mList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 大图预览相关变量
const previewAvatar = ref(''); // 预览的头像地址
const showAvatarDialog = ref(false); // 控制弹窗显示

// 查看大图
function viewAvatar(avatarUrl) {
  if (avatarUrl) {
    previewAvatar.value = avatarUrl;
    showAvatarDialog.value = true;
  } else {
    proxy.$modal.msgInfo("该用户暂无头像");
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    nickName: null,
    phone: null,
    email: null,
    password: null,
    avatar: null,
    regTime: null,
    defaultAddrId: null,
    status: null,
    deleted: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser_m(queryParams.value).then(response => {
    user_mList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userName: null,
    nickName: null,
    phone: null,
    email: null,
    password: null,
    avatar: null,
    regTime: null,
    defaultAddrId: null,
    status: null,
    deleted: null
  }
  proxy.resetForm("user_mRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加用户"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getUser_m(_id).then(response => {
    form.value = response.data
    console.log(form.value.id)
    open.value = true
    title.value = "修改用户"
  })
}

// 监听头像更新事件（子组件上传成功后触发）
const handleAvatarUpdated = (newAvatarUrl) => {
  // 1. 更新表单中的头像地址（确保表单显示新头像）
  form.value.avatar = newAvatarUrl;

  // 2. 更新列表中对应行的头像（实现列表实时回显）
  if (form.value.id) { // 仅修改时需要更新列表（新增时列表还未生成）
    const targetRow = user_mList.value.find(row => row.id === form.value.id);
    if (targetRow) {
      targetRow.avatar = newAvatarUrl; // 直接修改列表行数据，表格会自动刷新
    }
  }
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["user_mRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUser_m(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUser_m(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除用户编号为"' + _ids + '"的数据项？').then(function() {
    return delUser_m(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/user_m/export', {
    ...queryParams.value
  }, `user_m_${new Date().getTime()}.xlsx`)
}
getList()
</script>

<style scoped>
/* 头像图片样式 */
.avatar-img {
  width: 50px;  /* 头像宽度 */
  height: 50px; /* 头像高度 */
  border-radius: 50%; /* 圆形头像 */
  object-fit: cover; /* 保持图片比例，裁剪多余部分 */
  cursor: pointer; /* 鼠标悬停显示手型 */
  border: 1px solid #eee; /* 边框美化 */
}
</style>